<template>
  <div>
    <el-page-header class="mb15" @back="router.push('/competition/competitionManage')">
      <template #title>
        <span> 返回列表 </span>
      </template>
    </el-page-header>
    <el-card class="competition-card">
      <!-- 赛事信息 -->
      <div class="font20 mb30 font-weight">赛事信息</div>
      <el-form ref="ruleFormRef" :model="state.raceInfo" :rules="rules" label-position="top" label-width="120px"
        class="competition-ruleForm" :size="formSize" status-icon>
        <el-form-item label="赛事名称" prop="raceName">
          <el-input v-model="state.raceInfo.raceName" placeholder="请输入赛事名称" />
        </el-form-item>
        <el-form-item label="赛事logo" prop="raceLogo">
          <el-upload action="#" :show-file-list="false" accept=".png,.jpg" list-type="picture-card" :auto-upload="false"
            :on-change="handleAvatarSuccess">
            <img v-if="uploadImg" :src="uploadImg" class="competition-avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <img :src="file.url" alt="" class="competition-avatar" />
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="赛事组别" prop="raceGroup">
          <el-radio-group v-model="state.raceInfo.raceGroup">
            <el-radio v-for="item in groupList" :label="item.id">{{
              item.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赛事赛制" prop="raceSystem">
          <el-radio-group v-model="state.raceInfo.raceSystem">
            <el-radio v-for="item in competitionList" :label="item.id">{{
              item.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赛事类型" prop="raceType">
          <el-radio-group v-model="state.raceInfo.raceType">
            <el-radio v-for="item in competitionTypeList" :label="item.id">{{
              item.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赛事地点" prop="raceAddress">
          <el-input v-model="state.raceInfo.raceAddress" placeholder="请输入赛事地点" />
        </el-form-item>
        <el-form-item label="赛事规程" prop="raceRegulation">
          <div v-if="uploadFile" class="el-upload__tip">
            <el-link type="primary" target="_blank" :href="uploadFile">点击查看规程文件</el-link>
          </div>
          <el-upload v-else action="#" drag :limit="1" accept=".pdf" :auto-upload="false" :on-change="handleFileSuccess">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽文件到此 <em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">请上传PDF文件</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="报名时间" prop="registerStartDate">
          <el-col :span="11">
            <el-form-item prop="registerStartDate">
              <el-date-picker v-model="state.raceInfo.registerStartDate" type="date" placeholder="请选择报名开始日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col class="text-center" :span="2">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="registerEndDate">
              <el-date-picker v-model="state.raceInfo.registerEndDate" type="date" placeholder="请选择报名结束日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="比赛时间" prop="matchStartDate">
          <el-col :span="11">
            <el-form-item prop="matchStartDate">
              <el-date-picker v-model="state.raceInfo.matchStartDate" type="date" placeholder="请选择报名开始日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col class="text-center" :span="2">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="matchEndDate">
              <el-date-picker v-model="state.raceInfo.matchEndDate" type="date" placeholder="请选择报名结束日期"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="队伍数量（支）" prop="teamCount">
          <el-input v-model.number="state.raceInfo.teamCount" placeholder="请输入队伍数量" />
        </el-form-item>
        <el-form-item label="报名费用（元/队）" prop="registerFee">
          <el-input type="number" min="0" v-model.number="state.raceInfo.registerFee" placeholder="请输入报名费用" />
        </el-form-item>
        <el-form-item label="纪律保证金（元/队）" prop="earnestFee">
          <el-input type="number" min="0" v-model.number="state.raceInfo.earnestFee" placeholder="请输入纪律保证金" />
        </el-form-item>
      </el-form>

      <el-divider border-style="dashed" />

      <!-- 报名信息 -->
      <div class="font20 mb30 font-weight">报名信息</div>
      <el-form ref="ruleFormRef" :model="state.raceTeamConfigInfo" :rules="rules" label-position="top" label-width="120px"
        class="competition-ruleForm" :size="formSize" status-icon>
        <el-form-item label="选择报名角色" prop="teamIdentityConfigList">
          <el-checkbox-group v-model="state.raceTeamConfigInfo.teamIdentityConfigList" @change="handleCheck">
            <el-checkbox v-for="item in rulesList" :label="item.value"
              :disabled="defaultTeamCheck.indexOf(item.value) >= 0">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="报名人员能否兼任">
          <el-radio-group v-model="state.raceTeamConfigInfo.multiIdentityEnable">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报名人数设置">
          <div class="flex flex-warp mb10 ml10" v-for="it in state.raceTeamConfigInfo.racePlayerConfigInfoList">
            <span class="font14 font-normal mr10">{{ TeamNumbersText[it.identityType as keyof typeof TeamNumbersText]
            }}</span>
            <el-input-number :disabled="it.identityType === 'captain' ||
              it.identityType === 'head.coach'
              " :min="0" controls-position="right" v-model.number="it.min" />
            <div class="pl10 pr10">--</div>
            <el-input-number :disabled="it.identityType === 'captain' ||
              it.identityType === 'head.coach'
              " :min="it.min" controls-position="right" v-model.number="it.max" />
            <el-button class="ml10" @click="handleChange(it.identityType, it.requiredInfoList)">报名信息配置</el-button>
          </div>
        </el-form-item>
        <el-form-item label="球队信息设置">
          <el-checkbox-group v-model="state.raceTeamConfigInfo.requiredInfoList">
            <el-checkbox v-for="item in teamInfoList" :label="item.value"
              :disabled="defaultRequiredCheck.indexOf(item.value) >= 0">{{
                item.name
              }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label=" 球队附件设置">
          <el-checkbox-group v-model="state.raceTeamConfigInfo.requiredAttachmentInfoList">
            <el-checkbox v-for="item in teamAttachmentList" :label="item.value">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <el-divider border-style="dashed" />

      <!-- 规则设置 -->
      <div class="font20 mb30 font-weight">规则设置</div>
      <el-form ref="ruleFormRef" :model="state.raceRuleConfigInfo" :rules="rules" label-position="top" label-width="120px"
        class="competition-ruleForm" :size="formSize" status-icon>
        <el-form-item label="是否追加处罚">
          <el-radio-group v-model="state.raceRuleConfigInfo.additionalPenalty">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="停赛规则">
          <el-row class="font-normal ml10" v-for="re in state.raceRuleConfigInfo.suspendRuleInfoList">
            <el-col :span="4">
              <p>
                比赛累计&nbsp;&nbsp;{{ PenaltyTypeText[re.penaltyType as keyof typeof PenaltyTypeText] }}
              </p>
            </el-col>
            <el-col :span="4" class="ml10">
              <el-input type="number" min="0" v-model.number="re.count" />
            </el-col>
            <el-col :span="3" class="ml10">
              <p>张&nbsp;&nbsp;停赛</p>
            </el-col>
            <el-col :span="4">
              <el-input type="number" min="0" v-model.number="re.rounds" />
            </el-col>
            <el-col :span="2" class="ml10">
              <p>轮</p>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="积分规则">
          <el-row class="font-normal mb10 ml10" v-for="int in state.raceRuleConfigInfo.pointRuleInfoList">
            <el-col :span="2">
              <p>
                {{ SinglePeriodTypeText[int.periodType as keyof typeof SinglePeriodTypeText] }}
              </p>
            </el-col>
            <el-col :span="1" class="ml10">
              <p>胜</p>
            </el-col>
            <el-col :span="3">
              <el-input type="number" min="0" v-model.number="int.winScore" />
            </el-col>
            <el-col :span="1" class="ml10">
              <p>分</p>
            </el-col>
            <el-col :span="1">
              <p>负</p>
            </el-col>
            <el-col :span="3">
              <el-input type="number" min="0" v-model.number="int.loseScore" />
            </el-col>
            <el-col :span="1" class="ml10">
              <p>分</p>
            </el-col>
            <el-col :span="1">
              <p>平</p>
            </el-col>
            <el-col :span="3">
              <el-input type="number" min="0" v-model.number="int.drawScore" />
            </el-col>
            <el-col :span="1" class="ml10">
              <p>分</p>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="数据统计" prop="raceStatisticsInfoList">
          <el-checkbox-group v-model="state.raceRuleConfigInfo.raceStatisticsInfoList">
            <el-checkbox v-for="item in dataList" :label="item.value">{{
              item.name
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排名规则">
          <div class="flex flex-center">
            <el-button @click="handleRules" style="width: 100px">设置规则</el-button>
            <span class="font-normal" v-for="(item, index) in state.raceRuleConfigInfo.rankRuleInfoList">
              {{
                index + 1
              }}、{{ RankRuleText[item as keyof typeof RankRuleText] }}
            </span>
          </div>
        </el-form-item>
        <el-form-item class="mt35">
          <el-button type="primary" v-if="matchType === 0" :loading="loading" @click="submitForm(ruleFormRef)">
            发布
          </el-button>
          <el-button type="success" v-if="matchType === 1" :loading="loading" @click="submitForm(ruleFormRef)">
            更新
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <InfoDialog ref="infoDialogRef" :type="ruleType" :defaultList="defaultList" @submit-enroll="submitEnroll" />
    <RuleDialog ref="ruleDialogRef" :change-rule="changeRule" />
  </div>
</template>

<script lang="ts" setup>
import { UploadFilled } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, FormInstance, FormRules, UploadFile } from "element-plus";
import {
  groupList,
  competitionList,
  competitionTypeList,
  rulesList,
  dataList,
  teamInfoList,
  teamAttachmentList,
} from "./mock";
import InfoDialog from "./components/infoDialog.vue";
import RuleDialog from "./components/ruleDialog.vue";
import {
  TeamNumbersText,
  PenaltyTypeText,
  SinglePeriodTypeText,
  RankRuleText,
} from "../config/index";
import {
  postUploadImg,
  postAddMatch,
  postUpdateMatch,
  getMatchDetail,
} from "@/api/match";
import { useRoute, useRouter } from "vue-router";
import {
  TeamMemberRoleEnum,
  RegisterInfoEnum,
  TeamInfoEnum,
  TeamAttachmentEnum,
} from "../config/enum";

const route = useRoute();
const router = useRouter();
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const uploadImg = ref("");
const uploadFile = ref("");
const matchType = ref<number>(0);
const defaultTeamCheck = ref<string[]>([
  TeamMemberRoleEnum.PLAYER,
  TeamMemberRoleEnum.CAPTAIN,
  TeamMemberRoleEnum.HEAD_COACH,
]);
const defaultRequiredInfo = ref([
  RegisterInfoEnum.ID_NAME,
  RegisterInfoEnum.GENDER,
  RegisterInfoEnum.PHONE_NUMBER,
  RegisterInfoEnum.NATIONALITY,
  RegisterInfoEnum.ID_NUMBER,
  RegisterInfoEnum.ID_PHOTO,
]);
const defaultRequiredCheck = ref<string[]>([
  TeamInfoEnum.TEAM_NAME,
  TeamInfoEnum.TEAM_LOGO,
  TeamInfoEnum.TEAM_BRIEF,
]);
const loading = ref(false);
// 基础数据
const state = reactive({
  raceId: 0, // 赛事id
  // 赛事信息
  raceInfo: {
    raceName: "", //赛事名称
    raceLogo: "", //赛事logo
    raceGroup: "", //赛事组别
    raceSystem: "", //赛制
    raceType: "", //赛制类型
    raceAddress: "", //比赛地点
    raceRegulation: "", //赛事规程
    registerStartDate: "", //报名开始时间
    registerEndDate: "", //报名结束时间
    matchStartDate: "", //比赛开始时间
    matchEndDate: "", //比赛结束时间
    teamCount: "", //队伍数量
    registerFee: "", //报名费用
    earnestFee: "", //保证金
  },
  // 报名信息
  raceTeamConfigInfo: {
    teamIdentityConfigList: [
      TeamMemberRoleEnum.PLAYER,
      TeamMemberRoleEnum.CAPTAIN,
      TeamMemberRoleEnum.HEAD_COACH,
    ], //身份配置
    racePlayerConfigInfoList: [
      {
        identityType: TeamMemberRoleEnum.PLAYER,
        max: 0,
        min: 0,
        requiredInfoList: [
          RegisterInfoEnum.ID_NAME,
          RegisterInfoEnum.GENDER,
          RegisterInfoEnum.PHONE_NUMBER,
          RegisterInfoEnum.NATIONALITY,
          RegisterInfoEnum.ID_NUMBER,
          RegisterInfoEnum.ID_PHOTO,
          RegisterInfoEnum.PLAYER_NUMBER,
        ],
      },
      {
        identityType: TeamMemberRoleEnum.CAPTAIN,
        max: 1,
        min: 1,
        requiredInfoList: defaultRequiredInfo,
      },
      {
        identityType: TeamMemberRoleEnum.HEAD_COACH,
        max: 1,
        min: 1,
        requiredInfoList: defaultRequiredInfo,
      },
    ], //球队人员报名信息配置
    multiIdentityEnable: "Y", //人员身份兼任
    requiredInfoList: [
      TeamInfoEnum.TEAM_NAME,
      TeamInfoEnum.TEAM_LOGO,
      TeamInfoEnum.TEAM_BRIEF,
    ], //必填球队信息
    requiredAttachmentInfoList: [
      TeamAttachmentEnum.ENTRY_COMMITMENT,
      TeamAttachmentEnum.ENTRY_INSURANCE,
    ], //必填球队附件信息
  },
  // 规则设置
  raceRuleConfigInfo: {
    additionalPenalty: "Y", //追加处罚
    suspendRuleInfoList: [
      {
        penaltyType: "red", //处罚类型
        count: "", //红牌数
        rounds: "", //停赛轮数
      },
      {
        penaltyType: "yellow", //处罚类型
        count: "", //黄牌数
        rounds: "", //停赛轮数
      },
    ], //停赛规则
    pointRuleInfoList: [
      {
        periodType: "regular", //常规时间
        winScore: "", //胜分数
        drawScore: "", //平分数
        loseScore: "", //负分数
      },
      {
        periodType: "penalty.kick", //点球决胜
        winScore: "", //胜分数
        drawScore: "", //平分数
        loseScore: "", //负分数
      },
    ], //积分规则
    raceStatisticsInfoList: [], //数据统计
    rankRuleInfoList: [
      "team.scores",
      "total.goal.difference",
      "total.goal",
      "inter.outcome",
    ], //排名规则
  },
});

const rules = reactive<FormRules>({
  raceName: [{ required: true, message: "请输入赛事名称！", trigger: "blur" }],
  raceLogo: [
    {
      required: true,
      message: "请选择logo！",
      trigger: "change",
    },
  ],
  raceGroup: [
    {
      required: true,
      message: "请选择赛事组别！",
      trigger: "change",
    },
  ],
  raceSystem: [
    {
      required: true,
      message: "请选择赛事赛制！",
      trigger: "change",
    },
  ],
  raceType: [
    {
      required: true,
      message: "请选择赛事类型！",
      trigger: "change",
    },
  ],
  raceAddress: [
    { required: true, message: "请输入赛事地点！", trigger: "blur" },
  ],
  raceRegulation: [
    { required: true, message: "请输入赛事规程！", trigger: "blur" },
  ],
  registerStartDate: [
    { required: true, message: "请选择报名开始日期！", trigger: "change" },
  ],
  registerEndDate: [
    { required: true, message: "请选择报名结束日期！", trigger: "change" },
  ],
  matchStartDate: [
    { required: true, message: "请选择比赛开始日期！", trigger: "change" },
  ],
  matchEndDate: [
    { required: true, message: "请选择比赛结束日期！", trigger: "change" },
  ],
  teamCount: [{ required: true, message: "请输入队伍数量！", trigger: "blur" }],
  registerFee: [
    { required: true, message: "请输入报名费用！", trigger: "blur" },
  ],
  earnestFee: [
    { required: true, message: "请输入纪律保证金！", trigger: "blur" },
  ],
  raceStatisticsInfoList: [
    { type: "array", required: true, message: "请选择数据统计！", trigger: "blur" },
  ],
});
const infoDialogRef = ref();
const ruleType = ref("");
const defaultList = ref<string[]>([]);
const ruleDialogRef = ref();

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};
// 上传图片成功
const handleAvatarSuccess = async (file: UploadFile) => {
  const res = await postUploadImg({
    file: file.raw,
    fileType: "race",
  });
  state.raceInfo.raceLogo = res.data;
  uploadImg.value = URL.createObjectURL(file.raw!);
};
// 上传文件成功
const handleFileSuccess = async (file: UploadFile) => {
  const res = await postUploadImg({
    file: file.raw,
    fileType: "race",
  });
  state.raceInfo.raceRegulation = res.data;
};
// 报名角色 - 按钮
const handleCheck = (value: string[]) => {
  let arr = state.raceTeamConfigInfo.racePlayerConfigInfoList;
  let list: any = [];
  for (let i = 0; i < value.length; i++) {
    if (defaultTeamCheck.value.indexOf(value[i]) >= 0 || arr[i]?.max > 0) {
      list.push({
        identityType: value[i],
        max: arr[i].max,
        min: arr[i].min,
        requiredInfoList: arr[i].requiredInfoList,
      });
    } else {
      list.push({
        identityType: value[i],
        max: 0,
        min: 0,
        requiredInfoList: defaultRequiredInfo.value,
      });
    }
  }
  state.raceTeamConfigInfo.racePlayerConfigInfoList = list;
};
// 报名信息 - 报名信息配置按钮
const handleChange = (type: string, item: string[]) => {
  //1/球员, 2/领队, 3/主教练, 4/助理教练, 5/队务, 6/队医, 7/翻译, 8/技术分析员
  ruleType.value = type;
  defaultList.value = item;
  infoDialogRef.value.dialogVisible = true;
};

// 报名信息 - 报名设置
const submitEnroll = (arr: any) => {
  state.raceTeamConfigInfo.racePlayerConfigInfoList.map((item) => {
    if (item.identityType === ruleType.value) {
      item.requiredInfoList = arr;
    }
  });
  infoDialogRef.value.dialogVisible = false;
};

// 规则设置 - 排名规则设置按钮
const handleRules = () => {
  ruleDialogRef.value.dialogVisible = true;
};

// 规则设置 - 排名设置
const changeRule = (currentRule: any) => {
  state.raceRuleConfigInfo.rankRuleInfoList = currentRule;
};

// 发布/更新按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(state.raceTeamConfigInfo.racePlayerConfigInfoList, '===')
  let _configArr = state.raceTeamConfigInfo.racePlayerConfigInfoList;
  let _ruleArr = state.raceRuleConfigInfo.suspendRuleInfoList;
  let _pointArr = state.raceRuleConfigInfo.pointRuleInfoList;
  for (let i = 0; i < _configArr.length; i++) {
    if (_configArr[i].max === 0 && _configArr[i].min === 0) {
      return ElMessage({
        message: "请配置报名人数！",
        type: "warning",
      });
    }
  }
  for (let i = 0; i < _ruleArr.length; i++) {
    if (_ruleArr[i].count === "" || _ruleArr[i].rounds === "") {
      return ElMessage({
        message: "请配置停赛规则！",
        type: "warning",
      });
    }
  }
  for (let i = 0; i < _pointArr.length; i++) {
    if (_pointArr[i].winScore === "" || _pointArr[i].drawScore === "" || _pointArr[i].loseScore === "") {
      return ElMessage({
        message: "请配置积分规则！",
        type: "warning",
      });
    }
  }
  if (!formEl) return;
  try {
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        loading.value = true;
        if (matchType.value === 0) {
          await postAddMatch({
            raceInfo: state.raceInfo,
            raceTeamConfigInfo: state.raceTeamConfigInfo,
            raceRuleConfigInfo: state.raceRuleConfigInfo,
          });
        } else {
          await postUpdateMatch(state);
        }
        formEl.resetFields();
        ElMessage({
          message: `${matchType.value === 0 ? "发布" : "更新"}成功`,
          type: "success",
        });
        loading.value = false;
        router.push("/competition/competitionManage");
      }
    });
  } catch {
    loading.value = false;
  }
};

// 取消按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/competition/competitionManage");
};

// 获取赛事数据
const getMatchInfo = async (id: number) => {
  const res = await getMatchDetail({
    raceId: id,
  });
  if (res.code === 200) {
    uploadImg.value = res.data.raceInfo?.raceLogo;
    uploadFile.value = res.data.raceInfo?.raceRegulation;
    res.data.raceInfo.raceLogo = ""; // 清空数据，os：不修改则传空，修改则传上传接口返回路径（已与后端协商）
    state.raceId = res.data.raceId;
    state.raceInfo = res.data.raceInfo;
    state.raceTeamConfigInfo = res.data.raceTeamConfigInfo;
    state.raceRuleConfigInfo = res.data.raceRuleConfigInfo;
  }
};
// 初始化数据
onMounted(async () => {
  let { type, id } = route.query;
  matchType.value = Number(type);
  if (Number(type) != 0) {
    await getMatchInfo(Number(id));
  }
});
</script>

<style lang="scss" scoped>
.competition-ruleForm {
  min-width: 720px;
  margin-left: 80px;
  margin-right: 240px;
}

.competition-avatar {
  width: 100px;
  height: 100px;
}

.font-normal {
  font-weight: normal;
}

.font-weight {
  font-weight: 600;
}

.text-center {
  text-align: center;
}
</style>
<style>
.competition-ruleForm .el-form-item {
  font-weight: 600;
}
</style>
